<template>
  <div v-loading="loading">
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="120px"
      class="dataForm"
    >
      <el-row>
        <el-col :span="24">
          <el-form-item :label="$t('申请标题')" prop="actTitle">
            <el-input v-model="form.actTitle" :placeholder="$t('申请标题')" show-word-limit :maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('申请人')" prop="userId">
            <UserSelect
              v-model="form.userId"
              :placeholder="$t('选择用户')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('申请时间')" prop="applyTime">
            <DatePicker
              v-model="form.applyTime"
              :placeholder="$t('申请时间')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('报销总额(元)')" prop="amountMoney">
            <Money v-model="form.amountMoney" :placeholder="$t('手动维护或通过添加分摊明细自动计算')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('费用明细总额(元)')" prop="totalCostBreakdown">
            <Money v-model="form.totalCostBreakdown" disabled :placeholder="$t('手动维护或通过添加费用明细自动计算')" />
          </el-form-item>
        </el-col>
        <el-col
          v-if="form.payCompletionTime !== null && form.payCompletionTime !== '' && form.payCompletionTime !== undefined"
          :span="12"
        >
          <el-form-item :label="$t('付款完成时间')" prop="payCompletionTime">
            <DatePicker
              v-model="form.payCompletionTime"
              :disabled="true"
              value-format="yyyy-MM-dd"
              :placeholder="$t('申请时间')"
            />

          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('费用说明')" prop="costsThat">
            <el-input v-model="form.costsThat" type="textarea" :placeholder="$t('费用说明')" maxlength="2000" />
          </el-form-item>
        </el-col>
      </el-row>

      <div v-loading="ftmxLoading" class="mb-15">
        <!-- 分摊明细 -->
        <div class="area-header">
          <span class="area-header-title">{{ $t('分摊明细') }}</span>
        </div>
        <el-table
          :data="form.oaExpenseInvestorList"
          border
          class="nowrapTable formTable"
        >
          <el-table-column :label="$t('序号')" align="center" width="50">
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column :label="$t('主体类型')" align="center" min-width="130">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('主体类型') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'oaExpenseInvestorList.' + scope.$index + '.mainType'" :rules="oaExpenseInvestorListRules.mainType">
                <el-select v-model="scope.row.mainType" :placeholder="$t('请选择')" @change="scope.row.subject = ''; initSelectOption()">
                  <el-option
                    v-for="dict in mainBodyTypeAll"
                    :key="dict.dictValue"
                    :label="$t(dict.dictLabel)"
                    :value="dict.dictValue"
                  />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('费用主体')" align="center" min-width="130">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('费用主体') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'oaExpenseInvestorList.' + scope.$index + '.subject'" :rules="oaExpenseInvestorListRules.subject">
                <!--<el-select v-model="scope.row.subject" :placeholder="$t('请选择')">-->
                <!--  <el-option-->
                <!--    v-for="dict in mainBodyOptions[scope.row.mainType]"-->
                <!--    :key="dict.id"-->
                <!--    :label="dict.name"-->
                <!--    :value="dict.id"-->
                <!--  />-->
                <!--</el-select>-->
                <!--选择项目-->
                <el-select v-if="scope.row.mainType === 'deal'" v-model="scope.row.subject" filterable remote clearable :placeholder="$t('请选择')" :loading="dealSelectLoading" :remote-method="remoteMethodDeal">
                  <el-option
                    v-for="item in dealDataList"
                    :key="item.id"
                    :label="item.dealName"
                    :value="item.id"
                  />
                </el-select>
                <!-- 基金 -->
                <el-select v-else-if="scope.row.mainType === 'fund'" v-model="scope.row.subject" filterable clearable :placeholder="$t('请选择')">
                  <el-option
                    v-for="item in fundDataList"
                    :key="item.id"
                    :label="item.fundName"
                    :value="item.id"
                  />
                </el-select>
                <!--选择管理人-->
                <el-select v-else-if="scope.row.mainType === 'manager'" v-model="scope.row.subject" filterable clearable :placeholder="$t('请选择')">
                  <el-option
                    v-for="item in managerDataList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
                <!-- 内部机构 -->
                <el-select v-else-if="scope.row.mainType === 'internal'" v-model="scope.row.subject" filterable clearable :placeholder="$t('请选择')">
                  <el-option
                    v-for="item in internalDataList"
                    :key="item.id"
                    :label="item.interFullName"
                    :value="item.id"
                  />
                </el-select>
                <el-select v-else v-model="scope.row.subject" filterable clearable :placeholder="$t('请选择')">
                  <el-option
                    v-for="item in []"
                    :key="item.id"
                    :label="item.interFullName"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('承担部门')" align="center" min-width="130">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('承担部门') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'oaExpenseInvestorList.' + scope.$index + '.department'" :rules="oaExpenseInvestorListRules.department">
                <DeptSelect v-model="scope.row.department" :type="'table'" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('费用类型')" align="center" min-width="150">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('费用类型') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'oaExpenseInvestorList.' + scope.$index + '.typeArray'" :rules="oaExpenseInvestorListRules.typeArray">
                <el-cascader v-model="scope.row.typeArray" :options="getFdSubjectList" clearable>
                  <template slot-scope="{ node, data }">
                    <span>{{ $t(data.label) }}</span>
                    <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
                  </template>
                </el-cascader>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('金额(元)')" min-width="130">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('金额(元)') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'oaExpenseInvestorList.' + scope.$index + '.money'" :rules="oaExpenseInvestorListRules.money">
                <Money v-model="scope.row.money" @change="totalReimbursement" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column v-if="!otherBtnHide" fixed="right" :label="$t('操作')" align="center" width="100px">
            <template slot="header" slot-scope="{}">
              <el-tooltip placement="right">
                <span>{{ $t('操作') }}<i class="el-icon-question" /></span>
                <div slot="content">
                  <i class="el-icon-s-open" />: {{ $t('发票分摊工具') }}
                </div>
              </el-tooltip>
            </template>
            <template slot-scope="scope">
              <el-button v-hasPermi="['oa:expense:remove']" size="small" type="text" icon="el-icon-delete" @click="delInvestor(scope.$index,scope.row)" />
              <el-button v-hasPermi="['oa:expense:remove']" size="small" type="text" icon="el-icon-s-open" @click="apportionInvoice(scope.$index)" />
            </template>
          </el-table-column>
        </el-table>
        <div v-if="!otherBtnHide" class="tol">
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="addInvestor">{{ $t('添加主体') }}</el-button>
        </div>
      </div>
      <!--费用明细-->

      <div class="area-header detail-css-class">
        <span class="area-header-title">{{ $t('费用明细') }}
          <span class="content">
            <span class="text">
              <el-tooltip placement="right">
                <div slot="content">
                  {{ $t('支持识别的发票类型:') }} <br>
                  <span v-for="str in invoiceTypeExplain" :key="str">
                    {{ $t(str) }}<br>
                  </span>
                </div>
                <el-button class="tipText" type="text">
                  <i class="el-icon-question" style="color: black;" />
                </el-button>
              </el-tooltip>
            </span>
          </span>
        </span>
        <div class="query-result-msg">
          <span>{{ queryResultMsg }}</span>
        </div>
      </div>
      <div>
        <el-table
          v-loading="fymxLoading"
          :element-loading-text="fymxContextMsg"
          element-loading-spinner="el-icon-loading"
          :data="form.oaExpenseList"
          border
          class="nowrapTable formTable appendContent"
        >
          <el-table-column :label="$t('序号')" align="center" width="50">
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column :label="$t('发票')" align="center" min-width="130">
            <template slot-scope="scope">
              <div v-if="(((scope.row.typeMsg === undefined || scope.row.typeMsg === null) ? false : (scope.row.typeMsg.includes('增值税'))))" style="float: left;line-height: 3.1;color: #e08e00">
                <!-- 超过当前验查次数 -->
                <i v-if="scope.row.queryResult === '超过该张票当天查验次数'" :title="$t('发票查验失败, 超过验查次数. 请次日再试!')" class="el-icon-warning-outline" style="cursor: pointer;" @click="recheckInvoice(scope.row, scope.$index)" />
                <!-- 查验是否成功 -->
                <i
                  v-else-if="(scope.row.queryResult !== '查验成功' && scope.row.queryResult !== '免查验') && !queryResultArr.includes(scope.row.queryResult)"
                  :title="$t('发票查验失败, 可点击重试! 失败原因如下: 1.该发票不存在, 2.发票对接税务局验真的当天票据,可能存在未同步记录的情况!')"
                  class="el-icon-warning-outline"
                  style="cursor: pointer;"
                  @click="recheckInvoice(scope.row, scope.$index)"
                />
                <!-- 发票是否有误 -->
                <i
                  v-else-if="(scope.row.queryResult !== '查验成功' && scope.row.queryResult !== '免查验') && queryResultArr.includes(scope.row.queryResult)"
                  :title="(scope.row.queryResult === '金额错误') ? $t('识别金额与实际金额不符.') : '' + (scope.row.queryResult === '票号错误') ? $t('识别发票号与实际发票号不符.') : '' + $t('请将图片拍摄清晰后上传重试') + $t('1.图片不清晰, 识别出现错误!') + $t('2.该发票可能存在修改行为!')"
                  class="el-icon-warning-outline"
                  style="cursor: no-drop;color: red;"
                />
              </div>
              <div v-if="scope.row.fileList !== null && scope.row.fileList !== '' && scope.row.fileList !== undefined" style="width: 100%;">
                <div
                  class="link-type"
                  style="width: 85%;float: left;overflow: hidden;text-overflow:ellipsis;white-space: nowrap;"
                  @click="onlinePreview(scope.row.fileList)"
                >
                  <div class="content">
                    <div class="text">
                      <div :title="scope.row.fileList.name">
                        <el-button class="tipText" type="text">
                          {{ scope.row.fileList.name }}
                        </el-button>
                      </div>
                    </div>
                  </div>
                </div>
                <span
                  v-if="!otherBtnHide"
                  class="link-type"
                  style="line-height: 2.5;font-size: 14px;padding-right: 5px;float: right;position: absolute;color: darkslateblue;"
                  @click="deleteInvoice(scope.row)"
                >⊗</span>
              </div>
              <div v-if="scope.row.fileList === null || scope.row.fileList === '' || scope.row.fileList === undefined">
                <uploader
                  ref="uploader"
                  :options="options"
                  :auto-start="true"
                  class="uploader-app"
                  @file-added="onFileAdded($event, scope.$index)"
                  @file-success="onFileSuccess"
                  @file-error="onFileError"
                >
                  <uploader-btn
                    id="global-uploader-btn"
                    ref="uploadBtn"
                    style="font-weight: 500;border-radius: 4px;border: 1px solid;"
                    :attrs="attrs"
                  >{{ $t('上传发票') }}</uploader-btn>
                </uploader>
              </div>
            </template>
          </el-table-column>
          <el-table-column :label="$t('金额(元)')" min-width="130">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('金额(元)') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'oaExpenseList.' + scope.$index + '.money'" :rules="oaExpenseListRules.money">
                <Money v-model="scope.row.money" @change="getSummariesInput()" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('发生日期')" align="center" min-width="160">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('发生日期') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'oaExpenseList.' + scope.$index + '.time'" :rules="oaExpenseListRules.time">
                <DatePicker
                  v-model="scope.row.time"
                  type="date"
                  format="yyyy-MM-dd"
                  :placeholder="$t('发生日期')"
                />

              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('发票代码')" align="center" min-width="130">
            <template slot="header" slot-scope="{}">
              <span>{{ $t('发票代码') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'oaExpenseList.' + scope.$index + '.invoiceCode'" :rules="oaExpenseListRules.invoiceCode">
                <el-input v-model="scope.row.invoiceCode" :maxlength="50" :placeholder="$t('发票代码')" @input="inputInvoiceCode()" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('备注')" align="center" min-width="130">
            <template slot-scope="scope">
              <el-form-item prop="remark">
                <el-input v-model="scope.row.remark" type="textarea" maxlength="200" class="fileTextarea" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column fixed="right" :label="$t('操作')" align="center" width="80px">
            <template slot-scope="scope">
              <el-button v-if="configDownloadEnabled" size="small" type="text" class="el-icon-download" style="pointer-events: auto !important;cursor: pointer !important;" :disabled="scope.row.fileList === null || scope.row.fileList === undefined" @click="downloadFile(scope.row.fileList)" />
              <el-button v-if="!otherBtnHide" v-hasPermi="['oa:expense:remove']" size="small" type="text" icon="el-icon-delete" @click="delHandle(scope.$index,scope.row)" />
            </template>
          </el-table-column>
        </el-table>
        <div v-if="!otherBtnHide" class="tol">
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="addPayment">{{ $t('添加明细') }}</el-button>
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="addPaymentList">{{ $t('批量添加') }}</el-button>
          <el-button type="warning" icon="el-icon-folder-opened" size="mini" @click="openInvoiceFolder">{{ $t('发 票 夹') }}</el-button>
        </div>
      </div>

      <!-- 附件列表 -->
      <FileTable :list.sync="form.fileList" data-type="oa_expense" :btn-show="!otherBtnHide" />

      <OnlinePreview ref="OnlinePreview" />

      <el-dialog v-el-drag-dialog :title="$t('批量添加发票')" :visible.sync="uploaderOpen" :close-on-click-modal="false" width="50%" append-to-body :before-close="handleDialogClose">
        <Upload ref="upload" :single="single" :remind-user-status="false" :is-show-file-remark="false" :is-show-file-type="false" :data-type="'oa_expense'" @appendData="getData($event)" />
      </el-dialog>
    </el-form>
    <!-- 添加或修改发票夹对话框 -->
    <el-dialog :title="$t('发票夹')" :visible.sync="expenseInvoiceFolderLoading" :close-on-click-modal="false" width="80%" append-to-body>
      <expenseInvoiceFolderList ref="expenseInvoiceFolderList" @useInvoiceArr="useInvoiceArr" />
    </el-dialog>

    <!-- 快速计算至分摊明细 -->
    <el-dialog :title="$t('分摊发票工具')" :visible.sync="oaExpenseDistributeInvoiceLoading" :close-on-click-modal="false" width="80%" append-to-body>
      <oaExpenseDistributeInvoice ref="oaExpenseDistributeInvoice" @addApportionmentCalculation="addApportionmentCalculation" />
    </el-dialog>

    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存，保存并启动流程，取消 三个按钮-->
      <FormBtn ref="formBtn" :bus-data="form" has-permi="oa:expense" :btn-hide="btnHide" :menu-key="menuKey" />
    </div>
  </div>
</template>

<script>
    import expenseInvoiceFolderList from '@/views/oa/expense/expenseInvoiceFolderList.vue'
    import oaExpenseDistributeInvoice from '@/views/oa/expense/oaExpenseDistributeInvoice.vue'
    import SparkMD5 from 'spark-md5'
    import $ from 'jquery'
    import jsMd5 from 'js-md5'
    import { config } from '@/utils'
    import { ACCEPT_CONFIG } from '@/utils/config'
    import { saveOaExpense, getOaExpense, deleteOaExpenseDetail, getInfoType, checkInvoiceCode, delOaExpenseInvestor } from '@/api/oa/expense/oaExpense'
    import { getFdSubjectList } from '@/api/fd/config/getTypeMain'
    import { getToken } from '@/utils/auth'
    import { delFile, fileBaseMerging } from '@/api/file/fileBase'
    import { invoiceParse, recheckInvoice } from '@/api/file/invoice'
    import { moneyFormat } from '@/utils/ruoyi'
    import { getUserProfile } from '@/api/system/user'
    import { downLoadFileOpen } from '@/utils/zipdownload'
    import { findDealLimit } from '@/api/base/deal/dealBase'
    import { findFundFofLimit } from '@/api/fund/fundBase'
    import { findGpLimit } from '@/api/fund/gp/gpBase'
    import { findInternalLimit } from '@/api/fund/internal/internalBase'
    export default {
        components: {
          expenseInvoiceFolderList,
          oaExpenseDistributeInvoice
        },
        data() {
            const checkDuplicate = (rule, value, callback) => {
              if (this.invoiceCodeValidator) {
                if (this.invoiceCodeArray.length === 0) {
                  console.log('数组没有重复值')
                  this.invoiceCodeValidator = false
                  callback()
                } else {
                  /* if (value === undefined) {
                    const temp = rule.field.substring(rule.field.lastIndexOf('.') - 1)
                    var index = parseInt(temp.substring(0, 1))
                    if (!isNaN(index)) {
                      value = this.form.oaExpenseList[index].invoiceCode
                    }
                  } */
                  if (this.invoiceCodeArray.toString().includes('**')) {
                    this.invoiceCodeArray.some(item => {
                      const code = item.substring(0, item.indexOf(':'))
                      const username = item.substring(item.indexOf(':') + 1, item.lastIndexOf('**'))
                      if (code === value) {
                        callback(new Error(this.$t(username + ': 已使用!')))
                      }
                    })
                    callback()
                  } else {
                    if (this.invoiceCodeArray.includes(value)) {
                      callback(new Error(this.$t('重复发票')))
                    } else {
                      callback()
                    }
                  }
                }
              } else {
                callback()
              }
            }
            const checkMoneySize = (rule, value, callback) => {
              this.$nextTick(() => {
                // 报销总额是否合格
                this.totalReimbursementFlag = true
                // 报销总额与费用明细总额对比是否合格
                this.costComparisonFlag = true
                var totalCostBreakdown = parseFloat(this.form.totalCostBreakdown)
                if (!isNaN(totalCostBreakdown) && typeof totalCostBreakdown === 'number') {
                  totalCostBreakdown = parseFloat(totalCostBreakdown.toFixed(2))
                }
                var amountMoney = parseFloat(this.form.amountMoney)
                if (!isNaN(amountMoney) && typeof amountMoney === 'number') {
                  amountMoney = parseFloat(amountMoney.toFixed(2))
                }
                console.log('checkMoneySize校验 => 报销总额: ' + amountMoney + ' 类型:' + typeof (amountMoney) + '费用明细: ' + totalCostBreakdown + ' 类型:' + typeof (totalCostBreakdown))
                if (value === '' || value === undefined || value === null) {
                  callback(new Error(this.$t('必填信息')))
                } else {
                  if (amountMoney <= 0) {
                    this.totalReimbursementFlag = false
                    callback(new Error(this.$t('请输入报销总额')))
                  } else if (this.isEmpty(this.form.oaExpenseList)) {
                    callback()
                  } else if (totalCostBreakdown < amountMoney.toFixed(2)) {
                    this.costComparisonFlag = false
                    callback(new Error(this.$t('报销总额不能大于费用明细总额,请检查费用明细')))
                  } else {
                    callback()
                  }
                }
              })
            }
            return {
                // 菜单标识
                menuKey: 'oa_expense',
                // 是否隐藏保存按钮
                btnHide: false,
                openLocation: undefined,
                // 是否隐藏其它按钮
                otherBtnHide: false,
                options: {
                  target: config.baseURL + '/file/fileBase/uploadDocLib?dataType=oa_expense',
                  chunkSize: '2048000',
                  singleFile: true,
                  fileParameterName: 'file',
                  maxChunkRetries: 3,
                  testChunks: true, // 是否开启服务器分片校验
                  // 服务器分片校验函数，秒传及断点续传基础
                  checkChunkUploadedByResponse: function(chunk, message) {
                    const objMessage = JSON.parse(message)
                    if (objMessage.data !== null && objMessage.data.numbers !== null) {
                      return (JSON.parse(objMessage.data.numbers) || []).indexOf(chunk.offset + 1) >= 0
                    } else {
                      return false
                    }
                  },
                  headers: {
                    Authorization: getToken()
                  },
                  query() {}
                },
                attrs: {
                  accept: ACCEPT_CONFIG.getAll()
                },
                title: undefined,
                loading: false,
                fymxLoading: false,
                ftmxLoading: false,
                fymxContextMsg: 'loading...',
                uploaderOpen: false,
                // 表单参数
                form: {
                  // 当前用户
                  userId: undefined,
                  amountMoney: undefined,
                  totalCostBreakdown: undefined,
                  // 附件列表
                  fileList: [],
                  oaExpenseInvestorList: [],
                  // 费用明细
                  oaExpenseList: []

                },
                // 表单校验
                rules: {
                  userId: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  applyTime: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  amountMoney: [{ required: true, validator: checkMoneySize,	trigger: ['change'] }],
                  totalCostBreakdown: [{ required: false, message: this.$t('必填信息'),	trigger: ['change'] }],
                  actTitle: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }]
                },
                oaExpenseListRules: {
                  money: [{ required: true, message: this.$t('必填信息'),	trigger: ['blur', 'change'] }],
                  time: [{ required: true, message: this.$t('必填信息'),	trigger: ['blur', 'change'] }],
                  invoiceCode: [{ required: false, validator: checkDuplicate,	trigger: ['blur', 'change'] }]
                },
                oaExpenseInvestorListRules: {
                  mainType: [{ required: true, message: this.$t('必填信息'),	trigger: 'change' }],
                  subject: [{ required: true, message: this.$t('必填信息'),	trigger: 'change' }],
                  department: [{ required: true, message: this.$t('必填信息'),	trigger: 'change' }],
                  typeArray: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  costType: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  money: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }]
                },
                // 操作按钮默认不展示
                buttonShow: true,
                // 部门
                deptOptions: [],
                // 费用类型
                getFdSubjectList: [],
                fileList: [],
                single: false,
                // 发票支持类型说明
                invoiceTypeExplain: [],
                expenseInvoiceFolderLoading: false,
                // 快速分摊发票
                oaExpenseDistributeInvoiceLoading: false,
                selectedInvoice: [],
                mainBodyTypeAll: [],
                deptId: '',
                invoiceCodeValidator: false,
                // 所有发票code
                invoiceCodeArray: [],
                // 报销总额是否合格
                totalReimbursementFlag: true,
                // 费用明细总额是否合格
                totalCostBreakdownFlag: true,
                // 报销总额与费用明细总额对比是否合格
                costComparisonFlag: true,
                // 全局下载开关
                configDownloadEnabled: true,
                queryResultArr: ['金额错误', '票号错误'],
                queryResultMsg: '',
                queryPageSize: 30,
                dealSelectLoading: false,
                fundSelectLoading: false,
                managerSelectLoading: false,
                internalSelectLoading: false,
                dealDataList: [],
                fundDataList: [],
                managerDataList: [],
                internalDataList: [],
                dealDataListBak: [],
                fundDataListBak: [],
                managerDataListBak: [],
                internalDataListBak: []
            }
        },
        watch: {
          'form.oaExpenseList': {
            handler(val) {
              if (val) {
                var temp = 0
                val.forEach(item => {
                  temp += item.money
                })
                if (!isNaN(temp)) {
                  this.$set(this.form, 'totalCostBreakdown', temp)
                }
              }
            },
            deep: true
          },
          form: {
            handler() {
              this.$forceUpdate()
              if (!this.isEmpty(this.form.amountMoney)) {
                this.$refs.form.validateField('amountMoney')
              }
            },
            deep: true,
            immediate: true
          }
        },
        created() {
        },
        mounted() {
            this.$bus.$emit('async_done')
            // 费用类型
            getFdSubjectList('expense').then(response => {
              this.getFdSubjectList = this.changeSubjectList(response.data)
            })
            // 主体类型
            this.getDicts('main_body_type_all').then(response => {
              this.mainBodyTypeAll = response.data
            })
            // 全局下载开关
            this.getConfigKeyToDownload('enable_download').then(response => {
              this.configDownloadEnabled = (response.msg === 'true')
            })
        },
        methods: {
            changeSubjectList(val) {
              const arr = []
              if (val.length !== 0) {
                val.forEach(item => {
                  const obj = {}
                  obj.value = item.value
                  obj.label = this.$t(item.label)
                if (item.children && item.children.length > 0) {
                    obj.children = this.changeSubjectList(item.children)
                  }
                  arr.push(obj)
                })
              }
              return arr
            },
            // 初始化数据
            init(data) {
                this.loading = true
                this.quickApportionmentArray = {}
                this.invoiceCodeValidator = false
                // 费用明细的小问号
                getInfoType().then(response => {
                  if (response.data !== null && response.data !== '' && response.data !== undefined) {
                    this.invoiceTypeExplain = []
                    response.data.forEach(item => {
                      this.invoiceTypeExplain.push(item)
                    })
                  }
                })
                if (data != null && data !== '' && data.id !== undefined) {
                    var msgTip = true
                    getOaExpense(data.id).then(response => {
                        this.form = response.data
                        const money = this.form.totalCostBreakdown
                        // this.getSummariesInput()
                        if (this.form.oaExpenseList === null) {
                          this.form.oaExpenseList = []
                        }
                        if (this.form.oaExpenseInvestorList === null) {
                          this.form.oaExpenseInvestorList = []
                        }
                        // 判断是否存在验真失败的费用明细
                        var flag = false
                        this.form.oaExpenseList.forEach(item => {
                          if (item.queryResult !== '查验成功' && item.queryResult !== '免查验' && item.queryResult !== null) {
                            flag = true
                          }
                        })
                        console.log(flag, msgTip)
                        if (flag && msgTip) {
                          msgTip = false
                          this.queryResultMsg = this.$t('请注意, 当前存在验真失败的发票')
                        }
                        if (money) {
                          this.$nextTick(() => {
                            this.form.totalCostBreakdown = money
                          })
                        }
                        // 获取所有主体信息
                        this.getMainBodyList()
                    })
                } else {
                  this.reset()
                  getUserProfile().then(response => {
                    this.deptId = response.data.dept.id
                  })
                  // 获取所有主体信息
                  this.getMainBodyList()
                }
            },
            // 表单重置
            reset() {
                this.form = {
                id: undefined,
                userId: this.$store.state.user.userId,
                applyTime: new Date(),
                amountMoney: undefined,
                costsThat: undefined,
                actId: undefined,
                actStatus: '',
                remark: undefined,
                createBy: undefined,
                createTime: undefined,
                updateBy: undefined,
                updateTime: undefined,
                payCompletionTime: undefined,
                delFlag: undefined,
                oaExpenseList: [],
                fileList: undefined,
                getFdSubjectList: []
              }
              this.resetForm('form')
            },
            handleDialogClose() {
              this.uploaderOpen = false
            },
            // 下载发票
            downloadFile(row) {
              downLoadFileOpen(row.id)
            },
            // 打开发票价
            openInvoiceFolder() {
              this.expenseInvoiceFolderLoading = true
              this.$nextTick(() => {
                // 重复提交按钮禁用状态还原
                this.$refs.expenseInvoiceFolderList.disabledStatus = true
                // 多选按钮禁用
                this.$refs.expenseInvoiceFolderList.multiSelectButton = true
                // 页面中已经使用的发票号码
                this.$refs.expenseInvoiceFolderList.selectedInvoice = this.selectedInvoice
                this.$refs.expenseInvoiceFolderList.getList()
              })
            },
            // 添加分担主体
            addInvestor() {
              const row = {
                id: undefined,
                mainType: undefined,
                subject: undefined,
                money: undefined,
                costType: undefined,
                department: this.deptId
              }
              if (!(this.form.oaExpenseInvestorList instanceof Array)) {
                this.$set(this.form, 'oaExpenseInvestorList', [])
              }
              this.$nextTick(() => {
                this.form.oaExpenseInvestorList.push(row)
              })
            },
            // 删除分摊主体
            delInvestor(index, row) {
              const id = row.id
              var that = this
              console.log('删除分摊明细')
              if (id !== undefined && id !== '' && id != null) {
                this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
                  confirmButtonText: this.$t('确定'),
                  cancelButtonText: this.$t('取消'),
                  type: 'warning'
                })
                .then(function() {
                  delOaExpenseInvestor(id).then(response => {
                    if (response.code === 200) {
                      // 重新计算 分摊明细工具 index
                      that.recalculateAllocationDetailsTool(index)
                      that.form.oaExpenseInvestorList.splice(index, 1)
                      that.totalReimbursement()
                      return that.msgSuccess(that.$t('删除成功'))
                    } else {
                      that.msgError(that.$t(response.msg))
                    }
                  })
                }).then(() => {})
                .catch(function() {})
              } else {
                // 重新计算 分摊明细工具 index
                that.recalculateAllocationDetailsTool(index)
                that.form.oaExpenseInvestorList.splice(index, 1)
                // 重新计算金额
                that.totalReimbursement()
              }
            },
            // 添加付款主体
            addPayment() {
              const row = {
                id: undefined,
                mainType: undefined,
                subject: undefined,
                money: undefined,
                costType: undefined,
                time: undefined,
                queryResult: undefined,
                typeMsg: undefined,
                checkCode: undefined,
                department: this.deptId,
                fileList: undefined,
                remark: undefined
              }
              if (!(this.form.oaExpenseList instanceof Array)) {
                this.$set(this.form, 'oaExpenseList', [])
              }
              this.$nextTick(() => {
                this.form.oaExpenseList.push(row)
              })
            },
            // 删除付款主体
            delHandle(index, row) {
              const id = row.id
              if (id !== undefined && id !== '' && id != null) {
                this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
                  confirmButtonText: this.$t('确定'),
                  cancelButtonText: this.$t('取消'),
                  type: 'warning'
                })
                  .then(function() {
                    deleteOaExpenseDetail(id).then(() => {
                      // 计算总额
                      this.totalReimbursement()
                      this.getSummariesInput()
                      this.deleteFolderInvoiceCode(row)
                    })
                    return 1
                  }).then(() => {
                  this.form.oaExpenseList.splice(index, 1)
                  // 计算总额
                  this.totalReimbursement()
                  this.getSummariesInput()
                  this.deleteFolderInvoiceCode(row)
                  return this.msgSuccess(this.$t('删除成功'))
                })
                  .catch(function() {})
              } else {
                this.form.oaExpenseList.splice(index, 1)
                this.deleteFolderInvoiceCode(row)
                this.getSummariesInput()
              }
            },
            // 删除费用明细后 清除发票夹中已选择的发票
            deleteFolderInvoiceCode(row) {
              this.selectedInvoice.forEach((item, i) => {
                if (item === row.invoiceCode) {
                  this.selectedInvoice.splice(i, 1)
                  // 计算总额
                  this.totalReimbursement()
                  this.getSummariesInput()
                }
              })
            },
            // 取消按钮
            cancel() {
                if (this.$parent.$parent.formOpen !== undefined) {
                  this.$parent.$parent.formOpen = false
                }
                if (this.$parent.$parent.reset !== undefined) {
                  this.$parent.$parent.reset()
                }
            },
            // 关闭form页面
            closeForm() {
              // 关闭form页面遮罩层
              this.loading = false
              // 关闭form页面
              if (this.$parent.$parent.formOpen !== undefined) {
                this.$parent.$parent.formOpen = false
              }
              // 刷新list页面
              if (this.$parent.$parent.getList !== undefined) {
                this.$parent.$parent.getList()
              }
            },
            submitForm(type) {
              this.loading = true
              var submitFlag = true
              // 校验是否存在发票
              if (this.isEmpty(this.form.oaExpenseList)) {
                submitFlag = false
                this.msgError(this.$t('请添加一张发票明细!'))
                this.loading = false
              }
              // 报销总额是否合格
              if (!(this.totalReimbursementFlag && this.totalCostBreakdownFlag && this.costComparisonFlag)) {
                submitFlag = false
                this.loading = false
              }
              if (submitFlag) {
                this.invoiceCodeValidator = true
                return this.submitFormSave(type)
              }
            },
            /** 提交按钮 */
            submitFormSave: function(type) {
              var submitFlag = true
              // 校验前台表单中是否存在重复的发票
              if (this.form.oaExpenseList === null) {
                this.form.oaExpenseList = []
              }
              var temp = this.form.oaExpenseList
              // 记录table 中所有的重复发票号码
              this.invoiceCodeArray = []
              // 非重复数组
              var setArr = []
              // 重复数组
              var repeatArr = []
              temp.forEach(item => {
                if (!setArr.includes(item.invoiceCode) || item.invoiceCode === undefined || item.invoiceCode === '' || item.invoiceCode === null) {
                  setArr.push(item.invoiceCode)
                } else {
                  repeatArr.push(item.invoiceCode)
                }
              })
              if (temp.length !== setArr.length) {
                // 去重重复数组的重复元素
                const temp = new Set(repeatArr)
                temp.forEach(item => {
                  this.invoiceCodeArray.push(item)
                })
              }
              // 重新计算报销总额
              // this.getSummariesInput()
              // 首次校验当前页面中费用明细是否有重复
              console.log('第一次校验: 前台')
              this.$refs['form'].validate(valid => {
                // 验证数据
                if (!valid) {
                  submitFlag = false
                  this.loading = false
                  this.invoiceCodeValidator = true
                }
              })
              // 后台校验发票重复
              if (submitFlag) {
                return new Promise((resolve, reject) => {
                  // 一次校验发票是否已经存在
                  var invoiceIds = []
                  var tempInvoice = this.form.oaExpenseList
                  tempInvoice.forEach(item => {
                    // 只校验新增的 修改的时候就不校验了
                    if (item.id === '' || item.id === undefined || item.id === null) {
                      invoiceIds.push(item.invoiceCode)
                    }
                  })
                  invoiceIds = invoiceIds.join(',')
                  // 后台校验
                  checkInvoiceCode({ invoiceCode: invoiceIds }).then(Response => {
                    var secondFlag = true
                    if (Response.data !== null) {
                      var tempArr = []
                      var htmlMsg = ''
                      // 返回前台那些号码重复了
                      this.form.oaExpenseList.some(item => {
                        if (item.id === '' || item.id === undefined || item.id === null) {
                          Response.data.some(temp => {
                            var itemInvoiceCode = item.invoiceCode
                            if (itemInvoiceCode !== null && itemInvoiceCode !== undefined) {
                              itemInvoiceCode = itemInvoiceCode.trim()
                            }
                            var tempSubstring = temp.substring(0, temp.lastIndexOf(':'))
                            if (tempSubstring !== null && tempSubstring !== undefined) {
                              tempSubstring = tempSubstring.trim()
                            }
                            if (itemInvoiceCode === tempSubstring) {
                              htmlMsg += '<span>' + this.$t('发票:') + temp + this.$t('已被使用!') + '</span></br>'
                              tempArr.push(temp + '**')
                              submitFlag = false
                              secondFlag = false
                              this.loading = false
                            }
                          })
                          const temp = new Set(tempArr)
                          temp.forEach(item => {
                            this.invoiceCodeArray.push(item)
                            submitFlag = false
                            secondFlag = false
                            this.loading = false
                          })
                        }
                      })
                      if (htmlMsg !== '') {
                        this.$message({
                          dangerouslyUseHTMLString: true,
                          message: htmlMsg
                        })
                        this.loading = false
                      }
                    } else {
                      submitFlag = true
                      this.loading = false
                    }
                    console.log('第二次校验: 后台')
                    if (!submitFlag) {
                      this.invoiceCodeValidator = true
                      this.$refs['form'].validate(valid => {
                        // 验证数据
                        if (valid && secondFlag) {
                          submitFlag = true
                          this.loading = false
                        }
                      })
                    }
                    this.$refs['form'].validate(valid => {
                      // 验证数据
                      if (valid && submitFlag) {
                        // 给当前页面 发票明细加上序号
                        var count = 0
                        this.form.oaExpenseList.forEach(item => {
                          item.sort = count
                          count++
                        })
                        if (parseFloat(this.form.totalCostBreakdown).toFixed(2) > parseFloat(this.form.amountMoney).toFixed(2)) {
                          this.loading = false
                          this.$confirm(this.$t('报销总额与费用明细总额不相等, 是否继续?'), this.$t('警告'), {
                            confirmButtonText: this.$t('确定'),
                            cancelButtonText: this.$t('取消'),
                            type: 'warning'
                          }).then(() => {
                            this.saveData(resolve, reject, type)
                          }).catch(() => {
                            console.log('取消')
                            this.loading = false
                            reject()
                          })
                        } else {
                          this.saveData(resolve, reject, type)
                        }
                      } else {
                        this.loading = false
                        this.invoiceCodeValidator = false
                        this.locationError(document)
                        reject()
                      }
                    })
                  })
                })
              }
            },
            saveData(resolve, reject, type) {
              // 弹出遮罩层
              this.loading = true
              // 保存数据
              saveOaExpense(this.form).then(response => {
                if (response.code === 200) {
                  // 点击的按钮是保存并启动流程
                  if (type === 'process') {
                    // 设置数据id方式启动流程后取消并再次启动会创建多条记录
                    this.form = response.data
                    // 启动流程
                    this.startProcess(response.data)
                    // 点击的仅保存
                  } else {
                    this.msgSuccess(this.$t('保存成功'))
                    // 关闭form页面
                    this.closeForm()
                  }
                  resolve()
                } else {
                  this.msgError(response.msg)
                  this.loading = false
                  reject()
                }
              }).catch(() => {
                this.loading = false
              })
            },
            // 启动流程
            startProcess: function(data) {
              this.loading = false
              // 启动流程时候传入的参数
              const processData = {}
              // 待办标题
              processData.title = this.form.actTitle + '(' + moneyFormat(data.amountMoney) + ')'
              // 业务表名
              processData.dataTable = 'oa_expense'
              // 业务ID
              processData.dataId = data.id
              // 申请人ID
              processData.applyUserId = this.form.userId
              // 业务表单地址
              processData.formPath = '@/views/oa/expense/oaExpenseForm'
              // 业务表单打印地址
              processData.viewPath = '@/views/oa/expense/oaExpenseView'

              // 菜单标识(根据菜单标识判断的走哪个流程)
              processData.menuKey = this.menuKey
              this.startProcessByMenu(processData, () => {
                this.form.actStatus = 'D'
                this.msgSuccess(this.$t('数据保存成功,流程启动成功'))
                this.closeForm()
              })
            },
            // 汇总发票总额
            getSummariesInput() {
              var sum = 0
              if (this.form.oaExpenseList !== undefined && this.form.oaExpenseList !== null) {
                this.form.oaExpenseList.forEach(item => {
                  if (item.money === undefined || item.money === null || item.money === '' || isNaN(item.money)) {
                    item.money = 0
                  }
                  sum += parseFloat(item.money)
                  if (isNaN(sum)) {
                    sum = 0
                  }
                })
                // 汇总发票金额
                this.$set(this.form, 'totalCostBreakdown', sum)
              }
            },
            // 汇总报销总额
            totalReimbursement() {
              if (this.form.oaExpenseInvestorList !== undefined && this.form.oaExpenseInvestorList !== null && this.form.oaExpenseInvestorList !== '') {
                var sum = 0
                this.form.oaExpenseInvestorList.forEach(item => {
                  if (item.money === undefined || item.money === null || item.money === '') {
                    item.money = 0
                  }
                  sum += parseFloat(item.money)
                  if (isNaN(sum)) {
                    sum = 0
                  }
                })
                this.form.amountMoney = sum
              }
            },
            onFileAdded(file, index) {
              this.fymxContextMsg = 'loading...'
              this.listIndex = index
              this.fymxLoading = true
              // 设置文件md5
              this.computeMD5(file)
            },
            /**
             * 计算md5，实现断点续传及秒传
             * @param file
             */
            computeMD5(file) {
              const fileReader = new FileReader()
              // const time = new Date().getTime()
              const blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice
              let currentChunk = 0 // 当前分片
              const chunkSize = 10 * 1024 * 1000
              const chunks = Math.ceil(file.size / chunkSize) // 计算该文件一共有多少个分片
              const spark = new SparkMD5.ArrayBuffer() // 创建一个spark md5计算arrayBuffer的对象
              // 文件状态设为"计算MD5"
              file.pause()
              loadNext() // 首次读取文件分片
              // debugger
              // 当前分片读取完成
              fileReader.onload = e => {
                // debugger
                spark.append(e.target.result)
                if (currentChunk < chunks) {
                  currentChunk++
                  loadNext()
                  // 实时展示MD5的计算进度
                  this.$nextTick(() => {
                    $(`.myStatus_${file.id}`).text('校验MD5 ' + ((currentChunk / chunks) * 100).toFixed(0) + '%')
                  })
                } else {
                  // 最后一个分片，结束
                  file.uniqueIdentifier = spark.end() + '_' + jsMd5(file.name)
                  file.resume()
                }
              }
              fileReader.onerror = function() {
                this.error(this.$t('文件读取出错，请检查文件'))
                file.cancel()
              }
              function loadNext() { // 读取文件分片
                const start = currentChunk * chunkSize // 切片起始位置
                const end = ((start + chunkSize) >= file.size) ? file.size : start + chunkSize // 切片终止位置
                fileReader.readAsArrayBuffer(blobSlice.call(file.file, start, end)) // fileReader读取下一个文件分片
              }
            },
            onFileSuccess(rootFile, file, response) {
              this.fymxContextMsg = 'loading...'
              this.fymxLoading = true
              const res = JSON.parse(response)
              if (res.data !== null) {
                console.log(file.name + '文件上传阶段: ' + res.data.status + ',该文件存在的块数有: ' + JSON.parse(res.data.numbers))
                // 判断块是否全了. 不全的话重新上传
                if (JSON.parse(res.data.numbers).length === file.chunks.length) {
                  this.callbackMerge(file)
                } else {
                  console.log(file.name + '文件上传阶段: ' + res.data.status + ',该文件存在的块数有: ' + JSON.parse(res.data.numbers))
                  file.bootstrap()
                  file.retry()
                }
              } else {
                // 发生未知错误, 清理列表. (较大可能存在的原因:不同用户, 同一时间上传了MD5相同的附件)
                rootFile.clean()
              }
            },
            onFileError(error, file, fileList) {
              this.msgError(this.$t('上传失败, 请检查附件是否合法!'))
              console.log(error, file, fileList)
            },
            /**
             * 回调合并, 调用后台接口, 使其合并该文件
             * @param file
             */
            callbackMerge(file) {
              // 调用后台, 处理文件合并
              fileBaseMerging({
                identifier: file.uniqueIdentifier,
                dataType: 'oa_expense',
                totalSize: file.size,
                originalFilename: file.name,
                totalChunks: file.chunks.length,
                fileId: this.fileId
              }).then(response => {
                // 当前文件全部上传完成
                this.$bus.$emit('fileSuccess')
                // 设置文件的ID
                console.log(response)
                this.onFileSuccessComplete(file, response)
              }).catch(e => {
                console.error('文件合并回调失败!', e)
              })
            },
            onFileSuccessComplete(file, res) {
              if (String.valueOf(file.id).length < 32 || file.id === undefined || file.id === null) {
                file.id = res.data.fileId
              }
              this.$set(this.form.oaExpenseList[this.listIndex], 'fileList', file)
              // 识别发票
              this.invoiceParseMethod(file.id, file.name, 1, 1, 'single')
            },
            addPaymentList() {
              this.uploaderOpen = true
              this.title = '批量添加报销明细'
              this.single = false
            },
            getData(row) {
              this.fymxLoading = true
              var list = []
              row.fileList.forEach(item => {
                var temp = {
                  id: item.id,
                  name: item.name
                }
                list.push(temp)
              })
              this.uploaderOpen = false
              this.fymxLoading = false
              this.getDataASync(list)
            },
            // 过度方法, getData是子页面传来的 不太好用这里多加个方法过度一下
            getDataASync: async function(list) {
              try {
                var count = 1
                for (var i = 0; i < list.length; i++) {
                  await this.invoiceParseMethod(list[i].id, list[i].name, count, list.length, 'Multiple')
                  count++
                }
                // 重新计算 报销总额
                this.getSummariesInput()
              } catch (e) {
                console.log(e)
              }
            },
            // 开始识别发票并解析数据到页面
          /**
           *
           * @param fileId   发票ID
           * @param fileName 发票名
           * @param count  正在识别的发票序号
           * @param sum    上传总发票数量
           * @param type   单张上传方式还是多张 上传方式 Multiple: 多  single: 单
           * @returns {Promise<void>}
           */
            invoiceParseMethod: async function(fileId, fileName, count, sum, type) {
              try {
                // invoiceParse请求后台, 需要同步执行
                this.fymxLoading = true
                var msgPageInfo = '正在识别发票 <span style="color:red;">' + fileName + '</span> , <span style="color: blue;">共计' + sum + '张</span> <br/>正在识别<span style="color: orange">第' + count + '张</span>'
                try {
                  var suffix = fileName.split('.')
                  var suffixResult = suffix[suffix.length - 1]
                  if (
                    suffixResult !== 'pdf' &&
                    suffixResult !== 'PDF' &&
                    suffixResult !== 'JPG' &&
                    suffixResult !== 'PNG' &&
                    suffixResult !== 'JPEG' &&
                    suffixResult !== 'jpg' &&
                    suffixResult !== 'png' &&
                    suffixResult !== 'jpeg') {
                    msgPageInfo += '<br/><span style="color:red;">' + fileName + '</span>, 不能识别 <br/>仅支持图片和pdf类型!'
                  }
                  this.fymxContextMsg = '' + fileName + '[' + count + '/' + sum + ']'
                } catch (e2) {
                  console.log(e2)
                }
                this.$message({
                  dangerouslyUseHTMLString: true,
                  message: msgPageInfo
                })
                await invoiceParse(fileId).then(response => {
                  if (response.data.code !== 200 && response.data.code !== '200') {
                    this.fymxLoading = false
                    // 无法识别的票面也显示在table中
                    if (type !== 'single') {
                      var data = {
                        id: response.data.data[0].id,
                        fileName: response.data.data[0].fileName
                      }
                      this.addTableTrMethod(data)
                    }
                    this.msgError(response.data.message)
                  } else {
                    console.log('识别的发票展示到table, 第' + count + '张')
                    // 单图单张发票处理
                    var flagd = true
                    if (response.data.message.length <= 1) {
                      this.form.oaExpenseList.forEach((item, index) => {
                        if (item !== undefined && item !== null) {
                          if (item.fileList !== null && item.fileList !== undefined) {
                            if (item.fileList.id === fileId) {
                              var moneyTemps = response.data.message[0].money
                              if (moneyTemps === undefined || moneyTemps === null || moneyTemps === '') {
                                moneyTemps = 0
                              }
                              item.money = parseFloat(moneyTemps)
                              item.time = response.data.message[0].occurrenceTime
                              // item.invoiceCode = response.data.message[0].invoiceCode.trim()
                              this.$set(this.form.oaExpenseList[index], 'invoiceCode', response.data.message[0].invoiceCode.trim())
                              item.remark = response.data.message[0].description
                              item.typeMsg = response.data.message[0].typeMsg
                              item.checkCode = response.data.message[0].checkCode
                              item.queryResult = response.data.message[0].queryResult
                              // 页面上没有 table 的tr 里没有 这条数据那么添加一行
                              flagd = false
                            }
                          }
                        }
                      })
                      if (flagd) {
                        this.addTableTrMethod(response.data.message[0])
                      }
                      this.fymxLoading = false
                    } else {
                      // 识别出多张发票处理
                      // 情况1 添加按钮 后上传按钮哪里上传的图片, 图片中只存在一张发票 :  直接处理就好 最简单的方式 双for找table 中tr的文件id 和返回来的id相同就是了
                      // 情况2 添加按钮 后上传按钮哪里上传的图片, 图片中只存在多张发票 :  在table的tr 中找文件id 和 返回来的数据的id是否有相同的 相同说明 table中的tr里有 填上值
                      // 情况3 批量上传按钮 这里 为了方便 这里需要跑一下情况2 因为table 中的tr 的文件id 不存在id相同的 这个时候  直接走新添加行的方法就好
                      var countArr = []
                      // 情况1
                      this.form.oaExpenseList.forEach((item, index) => {
                        if (item.fileList !== null && item.fileList !== undefined) {
                          if (item.fileList.id === fileId) {
                            var moneyTemps = response.data.message[0].money
                            if (moneyTemps === undefined || moneyTemps === null || moneyTemps === '') {
                              moneyTemps = 0
                            }
                            item.money = parseFloat(moneyTemps)
                            item.time = response.data.message[0].occurrenceTime
                            // item.invoiceCode = response.data.message[0].invoiceCode.trim()
                            this.$set(this.form.oaExpenseList[index], 'invoiceCode', response.data.message[0].invoiceCode.trim())
                            item.remark = response.data.message[0].description
                            item.typeMsg = response.data.message[0].typeMsg
                            item.checkCode = response.data.message[0].checkCode
                            item.queryResult = response.data.message[0].queryResult
                            countArr.push(response.data.message[0].invoiceCode.trim())
                            debugger
                          }
                        }
                      })
                      // 剔除返回的数组中已经在页面上显示的 数据
                      var inputArr = []
                      if (countArr.length <= 0) {
                        inputArr = response.data.message
                      } else {
                        response.data.message.forEach(item => {
                          var itemInvoiceCode = item.invoiceCode
                          if (itemInvoiceCode !== null && itemInvoiceCode !== undefined) {
                            itemInvoiceCode = itemInvoiceCode.trim()
                          }
                          countArr.forEach(item2 => {
                            if (item2 !== itemInvoiceCode) {
                              inputArr.push(item)
                            }
                          })
                        })
                      }
                      // 情况2 和 3  说明table中没有相对的发票(tr)  新增(tr)
                      if (inputArr.length > 0) {
                        inputArr.forEach(item => {
                          this.addTableTrMethod(item)
                        })
                      }
                      this.fymxLoading = false
                    }
                  }
                  // 重新计算 报销总额 和 费用明细汇总
                  this.totalReimbursement()
                  this.getSummariesInput()
                })
              } catch (e) {
                console.log(e)
                this.fymxLoading = false
              }
            },
            // 后台返回的 新增数据的方法
            addTableTrMethod(item) {
              debugger
              var money = 0
              var moneyTemps = item.money
              if (moneyTemps === undefined || moneyTemps === null || moneyTemps === '') {
                moneyTemps = 0
              }
              money = parseFloat(moneyTemps)
              const row = {
                id: undefined,
                mainType: undefined,
                subject: undefined,
                costType: undefined,
                department: this.deptId,
                fileList: {
                  id: item.id,
                  name: item.fileName
                },
                money: money,
                time: item.occurrenceTime,
                invoiceCode: item.invoiceCode,
                remark: item.description,
                typeMsg: item.typeMsg,
                checkCode: item.checkCode,
                queryResult: item.queryResult
              }
              if (!(this.form.oaExpenseList instanceof Array)) {
                this.$set(this.form, 'oaExpenseList', [])
              }
              this.$nextTick(() => {
                this.form.oaExpenseList.push(row)
              })
            },
            // 预览附件
            onlinePreview(row) {
              this.$refs.OnlinePreview.onlinePreviewFile(row.id)
            },
            // 删除发票
            deleteInvoice(row) {
              this.fymxLoading = true
              delFile(row.fileList.id).then(response => {
                if (response.code === 200) {
                  row.fileList = null
                  this.msgSuccess(response.msg)
                } else {
                  this.msgError(response.msg)
                }
                this.fymxLoading = false
              })
            },
            // 重新查验发票
            recheckInvoice(row, index) {
              this.fymxLoading = true
              recheckInvoice(row).then(response => {
                console.log(response)
                if (response.data.result !== undefined) {
                  const result = response.data.result
                  result.desc
                  this.form.oaExpenseList[index].queryResult = result.desc
                }
                this.fymxLoading = false
              }).catch(() => {
                this.fymxLoading = false
              })
            },
            // 记录选择的发票
            useInvoiceArr(rows) {
              if (rows !== undefined && rows.length > 0) {
                rows.forEach((item, index) => {
                  this.selectedInvoice.push(item.invoiceCode)
                  var moneyTemps = item.money
                  if (moneyTemps === undefined || moneyTemps === null || moneyTemps === '') {
                    moneyTemps = 0
                  }
                  const row = {
                    id: undefined,
                    invoiceCode: item.invoiceCode,
                    money: moneyTemps,
                    time: item.time,
                    remark: item.remark,
                    typeMsg: item.typeMsg,
                    checkCode: item.checkCode,
                    queryResult: item.queryResult,
                    fileList: {
                      name: item.fileName,
                      id: item.invoiceId
                    }
                  }
                  if (!(this.form.oaExpenseList instanceof Array)) {
                    this.$set(this.form, 'oaExpenseList', [])
                  }
                  this.$nextTick(() => {
                    this.form.oaExpenseList.push(row)
                    if ((index + 1) === rows.length) {
                      // 重新计算 报销总额 和 费用明细汇总
                      this.totalReimbursement()
                      this.getSummariesInput()
                    }
                  })
                })
              }
            },
            // 快速分摊发票
            apportionInvoice(index) {
              this.oaExpenseDistributeInvoiceLoading = true
              this.$nextTick(() => {
                console.log('打开工具')
                // 确定剔除按钮 使用禁用
                this.$refs.oaExpenseDistributeInvoice.multiSelectButton = false
                // 防止重复提交初始化
                this.$refs.oaExpenseDistributeInvoice.disabledStatus = true
                this.$refs.oaExpenseDistributeInvoice.getList(this.form.oaExpenseList, index)
              })
            },
            // 累计分摊金额
            addApportionmentCalculation(data, oaExpenseInvoiceIndex) {
              console.log(data)
              var sum = 0
              this.form.oaExpenseList.forEach((item, index) => {
                // 清空
                if (item.index !== undefined && item.index === oaExpenseInvoiceIndex) {
                  item.index = undefined
                }
                // 重新给index
                if (data.includes(item)) {
                  this.form.oaExpenseList[index].index = oaExpenseInvoiceIndex
                  // 重新计算金额
                  if (item.money === undefined || item.money === '' || item.money === null) {
                    item.money = 0
                  }
                  item.money = parseFloat(item.money)
                  if (isNaN(item.money)) {
                    item.money = 0
                  }
                  sum += item.money
                }
              })
              this.form.oaExpenseInvestorList[oaExpenseInvoiceIndex].money = sum
              // 重新计算总额
              this.totalReimbursement()
            },
            // 重新计算 分摊明细工具 index
            recalculateAllocationDetailsTool(index) {
              // 清空要删的index
              this.form.oaExpenseList.forEach(item => {
                if (item.index !== undefined && item.index === index) {
                  item.index = undefined
                }
                // 其他分他明细对应的发票index 顺序调整
                if (index < this.form.oaExpenseInvestorList.length - 1 && index !== 0 && item.index !== undefined) {
                  if (item.index > index) {
                    item.index = item.index - 1
                  }
                }
              })
            },
          initSelectOption() {
            this.dealDataList = this.dealDataListBak
            this.fundDataList = this.fundDataListBak
            this.managerDataList = this.managerDataListBak
            this.internalDataList = this.internalDataListBak
          },
          remoteMethodDeal(query) {
            if (!this.isEmpty(query)) {
              this.dealSelectLoading = true
              findDealLimit({ pageSize: 30, pageNum: 1, dealName: query }).then(response => {
                this.dealDataList = (response.rows === null ? [] : response.rows)
                this.dealSelectLoading = false
              })
            } else {
              this.dealDataList = this.dealDataListBak
            }
          },
          // 获取所有主体下拉数据
          getMainBodyList() {
              var businessIdArr = []
              this.form.oaExpenseInvestorList && this.form.oaExpenseInvestorList.forEach(item => {
                if (!this.isEmpty(item.subject)) {
                  businessIdArr.push(item.subject)
                }
              })
              // 项目
              findDealLimit({ pageSize: this.queryPageSize, pageNum: 1, dealIdList: businessIdArr }).then(response => {
                this.dealDataListBak = this.dealDataList = (response.rows === null ? [] : response.rows)
                this.loading = false
              })
              // 基金
              findFundFofLimit({ pageSize: this.queryPageSize, pageNum: 1, fundIdList: businessIdArr }).then(response => {
                this.fundDataListBak = this.fundDataList = (response.rows === null ? [] : response.rows)
              })
              // 管理人
              findGpLimit({ pageSize: this.queryPageSize, pageNum: 1, gpIdList: businessIdArr }).then(response => {
                this.managerDataListBak = this.managerDataList = (response.rows === null ? [] : response.rows)
              })
              // 内部机构
              findInternalLimit({ pageSize: this.queryPageSize, pageNum: 1, internalIdList: businessIdArr }).then(response => {
                this.internalDataListBak = this.internalDataList = (response.rows === null ? [] : response.rows)
              })
          },
          inputInvoiceCode(val) {
              console.log(val)
              this.$forceUpdate()
          }
        }
    }
</script>
<style lang="scss" scoped>
  .query-result-msg {
    line-height: 2.5;
    right: 0;
    float: right;
    position: absolute;
    margin-right: 30px;
    color: orange;
  }
  .detail-css-class {
    display: inline-flex;
    width: 100%;
  }
</style>
